package cn.tedu.zookeeper;


import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZookeeperDemo2 {
    private ZooKeeper zk;
    //连接Zookeeper
    //zookeeper所有的连接和请求过程都是基于Netty来完成的
    //netty是基于NIO的异步非阻塞的通信框架
    //异步：测试线程和连接线程之间可以互相抢占的
    //非阻塞：无论是否建立连接 测试线程都可以先抢占往下执行
    @Before
    public void connect() throws IOException, InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        //参数 ip:port 会话超时时间 监控者，监控连接是否建立
        zk = new ZooKeeper("10.42.77.153:2181",
                5000,//现阶段要求范围在4000-40000之间
                e ->{
                    if (e.getState() == Watcher.Event.KeeperState.SyncConnected)
                        System.out.println("connected");
                    cdl.countDown();
                }
        );
        //需要等上面的线程线程执行完毕，才能继续往下执行
        cdl.await();
    }
    //监控节点的数据是否被修改
    @Test
    public void dataChanged() throws KeeperException, InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        zk.getData("/txt",e -> {
            if (e.getType() == Watcher.Event.EventType.NodeDataChanged)
                //实际开发中 需要记录入职
                System.out.println("数据被修改了");
            cdl.countDown();
        },null);
        cdl.await();
    }
    //子节点个数变化
    @Test
    public void childrenChanged() throws KeeperException, InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        zk.getChildren("/txt",e ->{
            if (e.getType() == Watcher.Event.EventType.NodeChildrenChanged)
                System.out.println("子节点个数变化");
            cdl.countDown();
        });
        cdl.await();
    }
    //节点的创建或者删除
    @Test
    public void nodeChanged() throws KeeperException, InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        zk.exists("/log",e -> {
            if (e.getType() == Watcher.Event.EventType.NodeCreated)
                System.out.println("节点被创建了");
            else if (e.getType() == Watcher.Event.EventType.NodeDeleted)
                System.out.println("节点被删除了");
            cdl.countDown();
        });
        cdl.await();
    }
}
